<?php require_once(dirname(__FILE__).'/../include/config.inc.php');
require_once "function.php";

$type						=  !empty($_GET['type']) ? htmlspecialchars($_GET['type']) : "1"  ; //报修类型
$apply_device_id	=  !empty($_GET['apply_device_id'])  ?    htmlspecialchars($_GET['apply_device_id']) : "1" ; //报修设备id


//获取用户的联系方式
if(isset($uid)){

		//有session 从数据库中读取用户名信息
	 	//$openid_str=$_SESSION['openid'];
		$row = $dosql->GetOne("SELECT * FROM `#@__user`  WHERE id='$uid'");
			if(is_array($row) && isset($row['id'])){
				// 返回用户 id 
				$userInfo=$row;
			}
}

//有联系方式，显示联系方式
$addressInfo="";
if($userInfo['school']!=""){
	$has_address=true;
	$addressInfo="<b>".$userInfo['school']."</b>".$userInfo['truename']."<i>".$userInfo['mobile']."</i><br/>".$userInfo['address'];
	$json_address=$userInfo['school'].'-'.$userInfo['address'];
}else{
	$has_address=false;
}



?>
<!DOCTYPE html>
<html>
<head>
<title>设备报修-<?php echo $cfg_webname;?></title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="description" content="<?php echo $cfg_webname;?>">
<link rel="stylesheet" href="lib/weui.min.css">
<link rel="stylesheet" href="css/jquery-weui.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<link rel="stylesheet" href="css/demos.css">
<link rel="stylesheet" href="/admin/ui/css/bootstrap.min.css">
<link rel="stylesheet" href="/admin/ui/css/bootstrap-theme.min.css" >
<script src="lib/jquery-2.1.4.js"></script> 
<script src="lib/fastclick.js"></script> 
<script>
  $(function() {
    FastClick.attach(document.body);
  });
</script> 
<script src="js/jquery-weui.js"></script> 
<script src="js/city-picker.js"></script> 
</head>

<body ontouchstart>
<div class="top"><a href="index.php"><img src="images/top.jpg" width="100%"></a> </div>
<?php
$sn_num="";
if(!isset($action)){
//获取参数中的条形码
$ma=htmlspecialchars($_GET['ma']);
$ma=urldecode($ma);
$sn_num=""; //设备序列号
$apply_name=""; // 设备名称
$typeidid="1";
if(isset($ma)){
	if(strstr($ma,"CODE") || strstr($ma,"EAN_13") ){
		$sn= explode(",", $ma);
		if(is_array($sn) && isset($sn[1])){
			$sn_num=$sn[1]; //设备序列号
			//从数据库中查询 设备序列号
			$row_sn = $dosql->GetOne("SELECT * FROM `#@__sn` WHERE `sn`='$sn_num' ");
			$school_sn="";
			$truename_sn="";
			$mobile_sn="";
			$address_sn="";
			$typename="";
			if(is_array($row_sn) && isset($row_sn['id']) ){
				$school_sn=$row_sn['school'];
				$truename_sn=$row_sn['truename'];
				$mobile_sn=$row_sn['mobile'];
				$address_sn=$row_sn['address'];
				$apply_device_id=$row_sn['typeid'];
				$typename=$row_sn['typename'];
			}else{
				echo '<script type="text/javascript">
				alert("您扫描的条形码不在条形码库，请您与客服人员联系沟通。");
			</script>';
			}
			
		}
	}else{
		$sn_num="";
		
		echo '<script type="text/javascript">
		alert("请扫描机身的条形码，谢谢");
		window.location.href="index.php";
	</script>';
	}
}else{
	echo "请扫描条形码";
	exit();
}

}
?>


<!-- 地址信息 -->
<form name="form" id="form" method="post" action="">
<div class="main ">
  <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i> 联系方式</div>
  <?php if($has_address){?>
  <div class="weui-cell bg-white">
    <div class="weui-cell__bd  myaddress"> <a href="address.php?call=apply&type=<?php echo $type;?>" class="weui-cell_access">
      <div class="myaddress_conn"><?php echo $addressInfo;?></div>
      <div class="myaddress_pic"><img src="images/go.png"></div>
       <input type="hidden" name="school" id="school" value="<?php echo $userInfo['school']?>">
       <input type="hidden" name="truename" id="truename" value="<?php echo $userInfo['truename']?>">
       <input type="hidden" name="mobile" id="mobile" value="<?php echo $userInfo['mobile']?>">
       <input type="hidden" name="address" id="address" value="<?php echo $userInfo['address']?>">
      </a> </div>
  </div>
  <?php }else{?>
    <div class="weui-cell weui-cells_form">
      <div class="weui-cell__hd">
        <label class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i> 单位：<span class="red">*</span> </label>
      </div>
      <div class="weui-cell__bd">
        <input class="form-control"  name="school" id="school" type="text"  value="<?php echo $school_sn?>">
      </div>
    </div>
    <div class="weui-cell">
      <div class="weui-cell__hd">
        <label class="weui-label"><i class="fa fa-user-circle-o" aria-hidden="true"></i> 联系人： <span class="red">*</span></label>
      </div>
      <div class="weui-cell__bd">
        <input class="form-control" name="truename" id="truename" type="text"   value="<?php echo $truename_sn?>">
      </div>
    </div>
    <div class="weui-cell ">
      <div class="weui-cell__hd">
        <label class="weui-label"><i class="fa fa-mobile" aria-hidden="true"></i>手机号： <span class="red">*</span></label>
      </div>
      <div class="weui-cell__bd">
        <input class="form-control" name="mobile" id="mobile" type="text"   value="<?php echo $mobile_sn?>">
      </div>
    </div>
    <div class="weui-cell">
      <div class="weui-cell__hd">
        <label class="weui-label"><i class="fa fa-map-marker" aria-hidden="true"></i>地址：</label>
      </div>
      <div class="weui-cell__bd">
        <input class="form-control" type="text" name="address"  id="address"  value="<?php echo $address_sn?>">
      </div>
    </div>
  <?php }?>
</div>




<!-- 报修信息 -->
<div class="main">
  <div class="weui-cells__title"><i class="fa fa-id-card-o" aria-hidden="true"></i> 在线报修</div>
  	<input type="hidden" id="latitude" name="latitude"> 
    <input type="hidden" id="longitude" name="longitude"> 
    <input type="hidden" id="accuracy" name="accuracy"> 
    <div class="weui-cells weui-cells_form">
      <div class="weui-cell">
      <div class="weui-cell__hd">
        <label for="" class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i> 设备：<span class="red">*</span></label>
      </div>
      <div class="weui-cell__bd">
        <select class="form-control" name="apply_device" id="apply_device" >
          <?php
						$dosql->Execute("SELECT * FROM  `#@__cascadedata`  WHERE  datagroup='device'   order by orderid asc ");
						while($row2 = $dosql->GetArray())
						{
							
							if ($apply_device_id==$row2['datavalue']){
								$selected = 'selected="selected"';
							}else{
								$selected = '';
							}
							echo '<option data-index="'.$row2['datavalue'].'"  value="'.$row2['datavalue'].'"  '.$selected.' >'.$row2['dataname'].'</option>';
						}
			?>
        </select>
      </div>
    </div>
    <div class="weui-cell">
      <div class="weui-cell__hd">
        <label class="weui-label"><i class="fa fa-building-o" aria-hidden="true"></i>序列号：</label>
      </div>
      <div class="weui-cell__bd">
        <input class="form-control"  name="device_num" id="device_num" type="text"   value="<?php echo $sn_num;?>" >
      </div>
    </div>
      <div class="weui-cells__title"> 故障描述<span class="red">*</span></div>
      <div class="weui-cells ">
        <div class="weui-cell">
          <div class="weui-cell__bd">
            <textarea class="form-control" name="content" id="content" placeholder="请输入文本" rows="3" onkeyup="words_deal();"><?php echo "故障设备类型：".$typename.";";?></textarea>
            <div class="weui-textarea-counter"><span id="textCount">0</span>/200</div>
          </div>
        </div>
      </div>
    </div>
    <!--上传 开始-->
    <div class="weui-cell">
      <div class="weui-cell__bd">
        <div class="weui-uploader">
          <div class="weui-uploader__hd">
            <p class="weui-uploader__title"> 图片上传<span class="red">*</span></p>
            <div class="weui-uploader__info">0/9</div>
          </div>
          
          <div class="weui-uploader__bd">
              <ul class="weui-uploader__files" id="uploaderFiles">
                
              </ul>
            <div class="weui-uploader__input-box">
              <input id="uploaderInput" class="weui-uploader__input" >
              <input type="hidden" name="picurls" id="picurls">
              <input type="hidden" name="picfiles" id="picfiles">
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--上传 结束-->
    <input type="hidden" name="action" id="action" value="add" />
    <input type="hidden" name="uid" id="uid" value="<?php echo $uid?>" />
    
  </form>
</div>
<div class="sub_btn"><a href="javascript:;" id="saoma_btn" class="weui-btn weui-btn_primary" onclick="<?php if($has_address){ echo "cfm_order()"; }else{ echo "cfm_order2()";   }?>;return false;">立即报修</a></div>
<div class="clear"></div>

<script>

  //描述字数限制
function words_deal()
  {
    var curLength=$("#content").val().length;
    if(curLength>200)
    {
      var num=$("#content").val().substr(0,200);
      $("#content").val(num);
      alert("超过字数限制，多出的字将被截断！" );
    }
    else
    {
      $("#textCount").text(200-$("#content").val().length);
    }
  }

//提交表单
function cfm_order()
{
	if($("#content").val() == "")
	{
		$.toast("请输入故障描述","forbidden");
		$("#content").focus();
		return false;
	}
	if($("#school").val() == ""){
		$.toast("请先完善联系方式","forbidden",function(){
			window.location.href="address.php?call=apply&type=<?php echo  $type?>";
		});
		
		return false;
	}
	$("#saoma_btn").hide();
	$("#form").submit();
}

function cfm_order2()
{
	if($("#school").val() == "")

	{

		$.toast("单位不能为空","forbidden");

		$("#school").focus();

		return false;

	}

	if($("#truename").val() == "")

	{

		$.toast("联系人不能为空","forbidden");

		$("#truename").focus();

		return false;

	}

	if($("#mobile").val() == "")

	{

		$.toast("手机号码不能为空","forbidden");

		$("#mobile").focus();

		return false;

	}


	
	if($("#content").val() == "")
	{
		$.toast("请输入故障描述","forbidden");
		$("#content").focus();
		return false;
	}

	$("#saoma_btn").hide();
	$("#form").submit();
}






    </script>
    
<?php


if(isset($action) and $action=='add'){
	if( empty($content)  )
	{
	echo '<script type="text/javascript">
	$.toast("操作不正确", function() {
		 window.location.href="index.php";
		});
	</script>';
		exit();
	}
	//如果是新客户，保存收货地址
	if(!$has_address){
		$school		=htmlspecialchars($school);
		$truename	=htmlspecialchars($truename);
		$mobile		=htmlspecialchars($mobile);
		$address		= htmlspecialchars($address);
		$json_address=$address."-".$school;
		$post_time					=time();
		//更新用户信息
		$sql_address="update  `#@__user` set school='$school',truename='$truename',mobile='$mobile',address='$address'  where id=$uid";
		$dosql->ExecNoneQuery($sql_address);
		
		//写入crm 
		$sql_crm = "INSERT INTO `#@__crm` (school, truename, mobile, address, addtime, checkinfo,uid) VALUES ( '$school','$truename', '$mobile', '$address', '$post_time', 'false','$uid')";
		$dosql->ExecNoneQuery($sql_crm);
		
	}
	// 工单信息入库
	$apply_device				= htmlspecialchars($apply_device);
	$content						= htmlspecialchars($content);
	$picurls						="";
	$jindu							="1";
	$post_time					=time();
	$post_time2				=date("Y-m-d H:i:s",time());
	

	//新建工单
	$sql2="insert into `#@__order`(openid,uid,school,truename,mobile,address,apply_type,apply_device,content,picurls,post_time,jindu,latitude,longitude,accuracy,picfiles,delstate,device_num) values ('$openid','$uid','$school','$truename','$mobile','$address','$type','$apply_device','$content','$picurls','$post_time','$jindu','$latitude','$longitude','$accuracy','$picfiles','','$device_num')";
	$dosql->ExecNoneQuery($sql2);

	
	$orderid=$dosql->GetLastID();
		//插入更新的状态
	$dosql->ExecNoneQuery("insert into `#@__order_log`(orderid,op,op_time,jindu) values ('$orderid','用户报修','$post_time','1')");
	$orderidname=date('Ymd',time())."-".$orderid;
	//封装为json格式的数据
	$json='{
	  "touser": "'.$openid.'" ,  
	  "template_id": "'.$cfg_apply.'",    
	  "url":"'.$cfg_weburl.'wx/orderDetail.php?orderid='.$orderid.'",      
	  "data": {
		  "first": {
			  "value": "您好，报修成功，即将派单维修", 
			  "color": "#f71b03"
		  }, 
		  "keyword1": {
			  "value": "'.$orderidname.'", 
			  "color": "#173177"
		  }, 
		  "keyword2": {
			  "value": "'.$post_time2.'", 
			  "color": "#173177"
		  },
		  "keyword3": {
			  "value": "'.getDeviceName($apply_device).'", 
			  "color": "#0e48cb"
		  },
		  "keyword4": {
			  "value": " '.$json_address.'", 
			  "color": "#173177"
		  },
		  "keyword5": {
			  "value": "'.$content.'", 
			  "color": "#173177"
		  },
		  "remark": {
			  "value": "系统正在派单，请稍等。马上会有工程师和您联系，请保持通讯畅通。服务热线：0396-2688801", 
			  "color": "#f71b03"
		  } 
	  }
	}';
	sendWxMsg($json);
	
	//封装为json格式的数据
	$json2='{
	  "touser": "'.$openid.'" ,  
	  "template_id": "'.$cfg_apply.'",    
	  "url":"'.$cfg_weburl.'wx/morderDetail.php?orderid='.$orderid.'",      
	  "data": {
		  "first": {
			  "value": "您好，用户通过扫码，报修成功，请登录后台处理", 
			  "color": "#f71b03"
		  }, 
		  "keyword1": {
			  "value": "'.$orderidname.'", 
			  "color": "#173177"
		  }, 
		  "keyword2": {
			  "value": "'.$post_time2.'", 
			  "color": "#173177"
		  },
		  "keyword3": {
			  "value": "'.getDeviceName($apply_device).'", 
			  "color": "#0e48cb"
		  },
		  "keyword4": {
			  "value": " '.$json_address.'", 
			  "color": "#173177"
		  },
		  "keyword5": {
			  "value": "'.$content.'", 
			  "color": "#173177"
		  },
		  "remark": {
			  "value": "等登录后台处理，先联系用户，再派单", 
			  "color": "#f71b03"
		  } 
	  }
	}';
	sendWxMsg($json2);
	
	echo '<script type="text/javascript">
	$.toast("报修成功", function() {
		 window.location.href="order.php";
		});
	</script>';
	exit();
	
}

?>    
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
  wx.config({
    debug: false,
    appId: '<?php echo $signPackage["appId"];?>',
    timestamp: <?php echo $signPackage["timestamp"];?>,
    nonceStr: '<?php echo $signPackage["nonceStr"];?>',
    signature: '<?php echo $signPackage["signature"];?>',
    jsApiList: [
      // 所有要调用的 API 都要加到这个列表中
	    'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
		'openAddress',
		'chooseImage',
		'previewImage',
		'uploadImage',
		'downloadImage'
    ]
  });
  wx.ready(function () {
	  // 分享
	  var urlurl=window.location.href;
	  var shareData = {
    	   title: '翰之博售后服务-在线报修',
    	   desc: '在线报修，2小时内响应。48-72小时内完修。维修状态实时查看。',
           link: urlurl,
           imgUrl: 'https://www.hanzhibo.cn/wx/images/zxbx.jpg'
	  };
	  
	  
	  wx.onMenuShareAppMessage(shareData);
	  wx.onMenuShareTimeline(shareData);
	  wx.onMenuShareQQ(shareData);
	  wx.onMenuShareQZone(shareData);
	//地址
	wx.getLocation({
		type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
		success: function (res) {
			var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
			$("#latitude").val(latitude);
			var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
			$("#longitude").val(longitude);
			var speed = res.speed; // 速度，以米/每秒计
			var accuracy = res.accuracy; // 位置精度
			$("#accuracy").val(accuracy);
 			$.ajax({ 
				url: "getMap.php?l="+latitude+"&w="+longitude,
				type:"GET",
				timeout:2000,
				dataType: "json",  
				success:function(data){
					console.log('ok');
					var gps_address=data.result.address_component.street;
					//alert(gps_address);
					$("#address").val(gps_address);
				},
				error: function(data) {            
					console.log('error');
					
				}  
			}); 
		},
		cancel: function (res) {
			 $.alert("你拒绝授权获取地理位置，我们的工程师无法快速定位。时效性可能会延时，请谅解", " 温馨提示");
		}
		
	});
	//打开相册
  var images = {
    localId: [],
    serverId: []
  };
  var filepaths="";
  document.querySelector('#uploaderInput').onclick = function () {
    wx.chooseImage({
      success: function (res) {
        images.localId = res.localIds;
		var picurls= res.localIds;
		var pic_count=res.localIds.length;
		$(".weui-uploader__info").html('已选择 ' + pic_count + ' 张图片');
		$("#picurls").val(picurls);
		//批量上传
		for(var i=0; i<pic_count; i++){
			wx.uploadImage({
				localId: picurls[i], // 需要上传的图片的本地ID，由chooseImage接口获得
				isShowProgressTips: 1, // 默认为1，显示进度提示
				success: function (res) {
					var serverId = res.serverId; // 返回图片的服务器端ID
					console.log(serverId);
						  $.ajax({
						  type: 'POST',
						  url: "getFile.php",
						  data: {serverId:serverId},
						  dataType: 'JSON',
						  success:function(result){
							if(result.errno==0){
								 console.log(result.msg);
								if(result.msg==="ok"){
									 filepaths+=result.filename+",";
									 $("#picfiles").val(filepaths);
									 $("#uploaderFiles").append('<li class="weui-uploader__file" style="background-image:url('+result.filename+')"></li>');
								}else{
									 $.alert("上传失败<br/> 请联系管理员！", "温馨提示");
								}
							}
						  }
					  });
				}
			});
		}
		$("#picfiles").val(filepaths);
		//批量上传
      }
    });
	
	
  };
  //
  
  
});
</script>    
<?php require_once('footer.php'); ?>